//
// Stick pack and half a pack 黏包半包
//

package addition.nio;

import org.junit.Test;

import java.nio.ByteBuffer;

public class SphpDemo {

    @Test
    public void test() {
        ByteBuffer source = ByteBuffer.allocate(1024);
        source.put("Hello, world\nI'm zhangsan\nHo".getBytes());
        split(source);
        source.put("w are you?\n".getBytes());
        split(source);
    }

    // 黏包半包处理
    public void split(ByteBuffer buf) {
        buf.flip();

        for (int i = 0; i < buf.limit(); i++) {
            if (buf.get(i) == '\n') {
                int len = i + 1 - buf.position();  // 一条记录的长度

                // 读取
                ByteBuffer target = ByteBuffer.allocate(len);
                for (int j = 0; j < len; j++) {
                    target.put(buf.get());
                }

                // 输出数据
                System.out.println(new String(target.array(), 0, len));
            }
        }

        buf.compact();  // 标记下次从上一次读写位置写入
    }

}
